import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export type Theme = 'light' | 'dark' | 'system'
export type Language = 'zh-CN' | 'en-US'

export const useGlobalStore = defineStore('global', () => {
  // 状态
  const theme = ref<Theme>((localStorage.getItem('theme') as Theme) || 'system')
  const language = ref<Language>((localStorage.getItem('language') as Language) || 'zh-CN')
  const sidebarCollapsed = ref(false)
  const loading = ref(false)
  const pageTitle = ref('')
  
  // 系统信息
  const systemInfo = ref({
    version: '1.0.0',
    buildTime: '',
    environment: import.meta.env.MODE,
    apiBaseUrl: import.meta.env.VITE_API_BASE_URL
  })

  // Toast消息队列
  const toasts = ref<Array<{
    id: string
    type: 'success' | 'error' | 'warning' | 'info'
    title: string
    message?: string
    duration?: number
  }>>([])

  // 全局错误信息
  const error = ref<{
    message: string
    code?: number
    timestamp: number
  } | null>(null)

  // 网络状态
  const isOnline = ref(navigator.onLine)

  // 计算属性
  const isDark = computed(() => {
    if (theme.value === 'system') {
      return window.matchMedia('(prefers-color-scheme: dark)').matches
    }
    return theme.value === 'dark'
  })

  const isZhCN = computed(() => language.value === 'zh-CN')

  // 设置主题
  const setTheme = (newTheme: Theme) => {
    theme.value = newTheme
    localStorage.setItem('theme', newTheme)
    updateThemeClass()
  }

  // 更新主题类名
  const updateThemeClass = () => {
    const root = document.documentElement
    if (isDark.value) {
      root.classList.add('dark')
    } else {
      root.classList.remove('dark')
    }
  }

  // 设置语言
  const setLanguage = (newLanguage: Language) => {
    language.value = newLanguage
    localStorage.setItem('language', newLanguage)
    // 这里可以触发i18n语言切换
  }

  // 切换侧边栏状态
  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
  }

  // 设置页面标题
  const setPageTitle = (title: string) => {
    pageTitle.value = title
    document.title = title ? `${title} - SSE-Coding` : 'SSE-Coding'
  }

  // 设置全局加载状态
  const setLoading = (isLoading: boolean) => {
    loading.value = isLoading
  }

  // 添加Toast消息
  const addToast = (toast: {
    type: 'success' | 'error' | 'warning' | 'info'
    title: string
    message?: string
    duration?: number
  }) => {
    const id = Date.now().toString()
    const newToast = {
      id,
      duration: 3000,
      ...toast
    }
    
    toasts.value.push(newToast)
    
    // 自动移除
    setTimeout(() => {
      removeToast(id)
    }, newToast.duration)
    
    return id
  }

  // 移除Toast消息
  const removeToast = (id: string) => {
    const index = toasts.value.findIndex(toast => toast.id === id)
    if (index > -1) {
      toasts.value.splice(index, 1)
    }
  }

  // 清空所有Toast
  const clearToasts = () => {
    toasts.value = []
  }

  // 设置全局错误
  const setError = (errorInfo: {
    message: string
    code?: number
  }) => {
    error.value = {
      ...errorInfo,
      timestamp: Date.now()
    }
  }

  // 清除错误
  const clearError = () => {
    error.value = null
  }

  // 初始化全局状态
  const initialize = () => {
    // 初始化主题
    updateThemeClass()
    
    // 监听系统主题变化
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    mediaQuery.addEventListener('change', () => {
      if (theme.value === 'system') {
        updateThemeClass()
      }
    })

    // 监听网络状态变化
    window.addEventListener('online', () => {
      isOnline.value = true
      addToast({
        type: 'success',
        title: '网络连接已恢复'
      })
    })

    window.addEventListener('offline', () => {
      isOnline.value = false
      addToast({
        type: 'warning',
        title: '网络连接已断开',
        message: '请检查您的网络连接'
      })
    })

    // 全局错误处理
    window.addEventListener('unhandledrejection', (event) => {
      console.error('Unhandled promise rejection:', event.reason)
      setError({
        message: '发生未处理的错误',
        code: -1
      })
    })

    window.addEventListener('error', (event) => {
      console.error('Global error:', event.error)
      setError({
        message: '页面发生错误',
        code: -1
      })
    })
  }

  // 获取系统配置
  const getSystemConfig = () => {
    return {
      theme: theme.value,
      language: language.value,
      sidebarCollapsed: sidebarCollapsed.value,
      ...systemInfo.value
    }
  }

  // 导出用户设置
  const exportSettings = () => {
    const settings = {
      theme: theme.value,
      language: language.value,
      sidebarCollapsed: sidebarCollapsed.value,
      exportTime: new Date().toISOString()
    }
    
    const blob = new Blob([JSON.stringify(settings, null, 2)], {
      type: 'application/json'
    })
    
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `sysu-question-settings-${Date.now()}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
  }

  // 导入用户设置
  const importSettings = async (file: File) => {
    try {
      const text = await file.text()
      const settings = JSON.parse(text)
      
      if (settings.theme && ['light', 'dark', 'system'].includes(settings.theme)) {
        setTheme(settings.theme)
      }
      
      if (settings.language && ['zh-CN', 'en-US'].includes(settings.language)) {
        setLanguage(settings.language)
      }
      
      if (typeof settings.sidebarCollapsed === 'boolean') {
        sidebarCollapsed.value = settings.sidebarCollapsed
      }
      
      addToast({
        type: 'success',
        title: '设置导入成功'
      })
      
      return true
    } catch (error) {
      console.error('Import settings error:', error)
      addToast({
        type: 'error',
        title: '设置导入失败',
        message: '文件格式不正确'
      })
      return false
    }
  }

  return {
    // 状态
    theme,
    language,
    sidebarCollapsed,
    loading,
    pageTitle,
    systemInfo,
    toasts,
    error,
    isOnline,
    
    // 计算属性
    isDark,
    isZhCN,
    
    // 方法
    setTheme,
    updateThemeClass,
    setLanguage,
    toggleSidebar,
    setPageTitle,
    setLoading,
    addToast,
    removeToast,
    clearToasts,
    setError,
    clearError,
    initialize,
    getSystemConfig,
    exportSettings,
    importSettings
  }
})

